package com.yh.ldzl.config.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器，处理认证和保存用户信息
 */
@Component
public class WebSocketAuthInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                                  WebSocketHandler wsHandler, Map<String, Object> attributes) {
        System.out.println("WebSocket握手开始 - URI: " + request.getURI());
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 获取token参数
            String token = servletRequest.getServletRequest().getParameter("token");
            
            if (token != null && !token.isEmpty()) {
                try {
                    // 简单验证，实际项目中应调用系统的认证服务
                    // 此处可以扩展连接系统的身份验证服务
                    attributes.put("userId", "user_" + System.currentTimeMillis());
                    attributes.put("token", token);
                    
                    System.out.println("WebSocket认证成功，token: " + token);
                    return true;
                } catch (Exception e) {
                    System.err.println("WebSocket认证异常: " + e.getMessage());
                }
            }
            
            // 以下代码仅用于开发测试，正式环境应删除
            // 允许没有token的连接，仅用于开发测试
            System.out.println("WebSocket认证: 没有提供有效token，使用匿名连接");
            attributes.put("userId", "anonymous_" + System.currentTimeMillis());
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                              WebSocketHandler wsHandler, Exception exception) {
        // 握手后操作，通常不需要处理
        if (exception != null) {
            System.err.println("WebSocket握手后出现异常: " + exception.getMessage());
        }
    }
}
